/**
 * @file    chatwindow.cpp
 * @author  Siddharth Sathyam <ssathy2@gmail.com>
 * @author  Alan Ruvalcaba <aruval3@gmail.com>
 * @author  Pat LaMontagna <plamontagna@gmail.com>
 * @version 1.0
 * @section LICENSE
 *
 * This program is property of Siddharth Sathyam, Alan Ruvalcaba, Pat LaMontagna.
 *
 * @section DESCRIPTION
 *
 * The chatWindow class allows the user to interact with their friends by chatting with them by text.
 */

#include "chatwindow.h"
#include "ui_chatwindow.h"
#include "QDebug"
#include "QTextEdit"
chatWindow::chatWindow(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::chatWindow)
{
    ui->setupUi(this);

    // Hardcode the AddBuddy attributes
    ui->sendButton->setIcon(QIcon(":icons/send.png"));
    ui->sendButton->setIconSize(QSize (51,41));
    ui->sendButton->setFlat(true);


    //Install filter to inputWindow to handle different keystroke inputs
    ui->inputWindow->installEventFilter(this);

    //Set keyboard focus to chat window when it is active
    ui->inputWindow->setFocus();

}

/*
  Destructor. Self explained
*/
chatWindow::~chatWindow()
{

    delete ui;

}

/*
Sends message based on user click on the send button
*/
void chatWindow::on_sendButton_clicked()
{
    QString currTime = QTime::currentTime().toString(Qt::TextDate);

    //Check if we aren't sending a blank message
    if(ui->inputWindow->toPlainText().trimmed().isEmpty())
	return;

    if(ui->timeStampCheckbox->isChecked())
    {
        QString currTime = QTime::currentTime().toString(Qt::TextDate);
	QString messagePretext = "<b>" + currTime + " " + this->fromUser + ": " + "</b>";

                ui->outputWindow->append(messagePretext);
               ui->outputWindow->insertPlainText(ui->inputWindow->toPlainText());

	//Signal for sending message to other user
	emit messageSent(this->fromUser,this->toUser,ui->inputWindow->toPlainText(),currTime);


	QString append = currTime + " " + this->fromUser + ": " + ui->inputWindow->toPlainText();

	//Write message to log if chatLogBox is enabled
	if(ui->chatLogBox->isChecked())
	{
	    this->OutPutChat(this->toUser,append);
	}

    }
    else
    {
	// need to do this to avoid a compiler error
	QString messagePretext ="<b>";
	QString restOfMessage =  messagePretext + " " + this->fromUser + ": " + "</b>";

       ui->outputWindow->append(restOfMessage);//Append html filled text
       ui->outputWindow->insertPlainText(ui->inputWindow->toPlainText());//Append regular message

	emit messageSent(this->fromUser,this->toUser,ui->inputWindow->toPlainText(),"");

	QString append = currTime + " " + this->fromUser + ": " + ui->inputWindow->toPlainText();

	//Write message to log if chatLogBox is enabled
	if(ui->chatLogBox->isChecked())
	{
	    this->OutPutChat(this->toUser,append);
	}
    }

    ui->inputWindow->clear();
}

/*
Below series of setters and getters for the 2 users communicating
*/
void chatWindow::setToUser(QString toUser)
{
    this->toUser = toUser;

}

void chatWindow::setfromUser(QString fromUser)
{
    this->fromUser = fromUser;
}

QString chatWindow::getToUser()
{
    return this->toUser;
}

QString chatWindow::getFromUser()
{
    return this->fromUser;
}

/*
Function below outputs message to appropriate chat log file
*/
void chatWindow::OutPutChat(QString name,QString message)
{
    //Acquire location of user home
    QString fileLocation = QDir::homePath();

    QString tempFileLocation = fileLocation;

    //Append file name and extension to correct Os
    if(getOsType() == "Windows")
    {

	//Create a QDir to the path where ChatLogs are stored
	QDir *tempFolder = new QDir(tempFileLocation.append("\\ChatLogs"));

	if(!tempFolder->exists())
	{

	    QDir *newLogFolder = new QDir(fileLocation);

	    //Create the chatLog folder
	    newLogFolder->mkdir("ChatLogs");

	    //Delete pointers
	    delete tempFolder;
	    delete newLogFolder;
	}
	fileLocation.append("\\ChatLogs");
	fileLocation.append("\\" + name +".txt");

    }

    else if(getOsType() == "Linux" || getOsType() == "Mac")
    {


	//Create a QDir with a path to the default ChatLog location
	QDir *tempFolder = new QDir(tempFileLocation.append("/ChatLogs"));
	if(!tempFolder->exists())
	{

	    QDir *newLogFolder = new QDir(fileLocation);

	    //Create the folder if it doesn't exist
	    newLogFolder->mkdir("ChatLogs");

	    //Delete pointers
	    delete tempFolder;
	    delete newLogFolder;
	}

	//append appropriate path
	fileLocation.append("/ChatLogs");
	fileLocation.append("/" + name +".txt");
    }

    //Create a QFile using path to chat log text file
    QFile file(fileLocation);

    //Open the file with follow Attributes: Being able to append,Read/write, and Text ensures
    //special chaarcters are endcoded properly such as \n \r etc
    //Qt takes care of file not exisiting by creating it for you
    file.open(QIODevice::Append | QIODevice::ReadWrite | QIODevice::Text);

    //Create a QTextStream to write to chat log file
    QTextStream out(&file);

    //Append message
    out << message <<endl;

    //Flush and close file
    file.close();
}

/*
Function to determine client's operating system. Useful for ChatLogging
*/
QString chatWindow::getOsType() {
#ifdef Q_WS_X11

    return QString("Linux");
#endif


#ifdef Q_WS_MAC
    return QString("Mac");

#endif

#ifdef Q_WS_QWS
    return QString("Linux");

#endif

#ifdef Q_WS_WIN
    return QString("Windows");

#endif
}

/*
Rewrote the eventFilter for the inputWindow. This handles both a return and a shift/control + enter
Return sends message while shift/control + adds a new line and moves cursor to the beginning of that line
*/
bool chatWindow::eventFilter(QObject *ob, QEvent *e)
{

    QKeyEvent *keyEvent = static_cast<QKeyEvent*>(e);

    //Check if the object requesting for an event is indeed the inputWindow
    if(ob == ui->inputWindow)
    {

	//Check for combination of keys
	if(keyEvent->key() == Qt::Key_Return && e->type() == QEvent::KeyPress && (keyEvent->modifiers() == Qt::ShiftModifier || keyEvent->modifiers() == Qt::ControlModifier ))
	{
	    //Move cursor down 1 line for every combination
            ui->inputWindow->append("<br/>");
	    return true;
	}

	//Check for just return key pressed and send message
	else if(keyEvent->key() == Qt::Key_Return && e->type() == QEvent::KeyPress)
	{

	    //Make sure we are not sending an empty message
            if(!ui->inputWindow->toPlainText().trimmed().isEmpty())
	    {
                 QString currTime = QTime::currentTime().toString(Qt::TextDate);
		if(ui->timeStampCheckbox->isChecked())
		{
		    //Signal for sending message
		    emit messageSent(this->fromUser,this->toUser,ui->inputWindow->toPlainText(),QTime::currentTime().toString(Qt::TextDate));



                    QString messagePretext = "<b>" + currTime + " " + this->fromUser + ": " + "</b>";
                    ui->outputWindow->append(messagePretext);//Append html filled text
                    ui->outputWindow->insertPlainText(ui->inputWindow->toPlainText());//Append plain text message

		    QString append = QTime::currentTime().toString(Qt::TextDate) + " " + this->fromUser + ": " + ui->inputWindow->toPlainText();

		    //Check if the Chat log box is enabled and write to file
		    if(ui->chatLogBox->isChecked())
		    {
			this->OutPutChat(this->toUser,append);
                    }

		    //Clear input window and move text cursor to up 1 line to accomodate for the \n appended for pressing enter
		    ui->inputWindow->clear();
		    QTextCursor temp = ui->inputWindow->textCursor();
		    temp.movePosition(QTextCursor::Up,QTextCursor::MoveAnchor);
		    ui->inputWindow->setTextCursor(temp);
		    return true;
		}
		else
		{
		    emit messageSent(this->fromUser,this->toUser,ui->inputWindow->toPlainText(), "");


                    // need to do this to avoid a compiler error
                    QString messagePretext ="<b>";
                    QString restOfMessage =  messagePretext + " " + this->fromUser + ": " + "</b>";

                   ui->outputWindow->append(restOfMessage);//Append html filled message
                   ui->outputWindow->insertPlainText(ui->inputWindow->toPlainText());//Append regular message

		    QString append = QTime::currentTime().toString(Qt::TextDate) + " " + this->fromUser + ": " + ui->inputWindow->toPlainText();

		    //Check if the Chat log box is enabled and write to file
		    if(ui->chatLogBox->isChecked())
		    {
			this->OutPutChat(this->toUser,append);
		    }

		    //Clear input window and move text cursor to up 1 line to accomodate for the \n appended for pressing enter
		    ui->inputWindow->clear();
		    QTextCursor temp = ui->inputWindow->textCursor();
		    temp.movePosition(QTextCursor::Up,QTextCursor::MoveAnchor);
		    ui->inputWindow->setTextCursor(temp);
		    return true;
		}
	    }
	}
	return false;
    }
    return false;
}

/*
Slot initiated after contactlist signals appropriate chat window for receiving a message.
*/
void chatWindow::receiveMessage(QString message,QString fromUser,QString time)
{
    QString messToDisplay = "<b>" + time + " " + fromUser + ": " + "</b>";

    ui->outputWindow->append(messToDisplay);//Append html filled message
    ui->outputWindow->insertPlainText(message);//Append regular message

    QString mess = time + " " + fromUser + ": " + message;

    //Check if the chatLogBox is enabled in order to write message to chat log file
    if(ui->chatLogBox->isChecked())
    {
	this->OutPutChat(fromUser,mess);
    }
}
